import cv2
import os
import numpy as np

video_path = r"D:\tennis\代码与模型数据\data\raw\Jannik Sinner vs Carlos Alcaraz Extended Highlights ｜ Indian Wells 2024 [P3eXD15w7So].webm"
output_dir = r"D:\tennis\代码与模型数据\data\images"
os.makedirs(output_dir, exist_ok=True)

cap = cv2.VideoCapture(video_path)
frame_rate = 2  # 每隔多少秒保存一帧
fps = cap.get(cv2.CAP_PROP_FPS)
interval = int(fps * frame_rate)

count = 0
saved = 0

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    if count % interval == 0:
        filename = os.path.join(output_dir, f"frame_{saved:04d}.jpg")

        # ⚠ 用 imencode + tofile 保存，支持中文路径
        ok, buf = cv2.imencode(".jpg", frame)
        if ok:
            buf.tofile(filename)
            print(f"[INFO] 保存成功: {filename}")
            saved += 1
        else:
            print(f"[ERROR] 保存失败: {filename}")

    count += 1

cap.release()
print(f"[INFO] 任务完成，共保存 {saved} 帧到 {output_dir}")
